package org.linuxsogood.boot.misc;

import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.*;

/**
 * @author honway.liu
 * @date 2019-03-07 22:20
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 */
@Slf4j
public class ConcurrencyTest {

    private static final int concurrencyNum = 200;
    private static final int totalRequest = 5000;
    //private static List<String> list = new ArrayList<>();
    private static List<String> list = new CopyOnWriteArrayList<>();

    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(concurrencyNum);
        CountDownLatch countDownLatch = new CountDownLatch(totalRequest);

        ExecutorService threadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < totalRequest; i++) {
            threadPool.execute(() -> {
                try {
                    semaphore.acquire();
                    method();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }

        try {
            countDownLatch.await();
            threadPool.shutdown();
            log.info("list size:{}", list.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void method() {
        list.add("a");
    }
}
